package com.xjscrm.console.service.customer.operatePlan.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.xjscrm.common.constant.ResponseMsg;
import com.xjscrm.common.entity.*;
import com.xjscrm.common.exception.BusinessException;
import com.xjscrm.common.result.ResponseCode;
import com.xjscrm.common.utils.OrderByUtil;
import com.xjscrm.console.mapper.*;
import com.xjscrm.console.param.operatePlan.*;
import com.xjscrm.console.param.wwCustomer.BatchDeleTagKeywordDeviceDto;
import com.xjscrm.console.param.wwCustomer.CustomerTagQuery;
import com.xjscrm.console.param.wwDevice.WwDeviceQuery;
import com.xjscrm.console.service.customer.operatePlan.TagKeywordService;
import com.xjscrm.console.vo.MyPageInfo;
import com.xjscrm.console.vo.TaskTagKeywordDeviceVo;
import com.xjscrm.console.vo.TaskTagKeywordVo;
import com.xjscrm.console.vo.WwDeviceVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class TagKeywordServiceImpl implements TagKeywordService {

    @Autowired
    private TagKeywordMapper tagKeywordMapper;

    @Autowired
    private WwTagsMapper wwTagsMapper;

    @Autowired
    private TaskTagKeywordDeviceMapper taskTagKeywordDeviceMapper;

    @Autowired
    private DeviceGroupRelationMapper deviceGroupRelationMapper;

    @Autowired
    private WwDeviceMapper  wwDeviceMapper;
    @Override
    public void addTagKeyword(TaskTagKeywordDto taskTagKeywordDto) {
        if(taskTagKeywordDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(taskTagKeywordDto.getName()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if(taskTagKeywordDto.getTriggerTypeList()==null||taskTagKeywordDto.getTriggerTypeList().isEmpty()){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if(taskTagKeywordDto.getKeywordType()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if(taskTagKeywordDto.getKeywordsList()==null||taskTagKeywordDto.getKeywordsList().isEmpty()){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if(taskTagKeywordDto.getEnterpriseTagsList()==null||taskTagKeywordDto.getEnterpriseTagsList().isEmpty()){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }

        TaskTagKeyword taskTagKeyword = new TaskTagKeyword();
        BeanUtil.copyProperties(taskTagKeywordDto,taskTagKeyword);
        taskTagKeyword.setTriggerType(JSONObject.toJSONString(taskTagKeywordDto.getTriggerTypeList()));
        taskTagKeyword.setKeywords(JSONObject.toJSONString(taskTagKeywordDto.getKeywordsList()));
        taskTagKeyword.setEnterpriseTags(taskTagKeywordDto.getEnterpriseTagsList().toString());
        tagKeywordMapper.addTaskTagKeyword(taskTagKeyword);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addTagKeywordDevice(TagKeywordDeviceDto tagKeywordDeviceDto) {
        if(tagKeywordDeviceDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(tagKeywordDeviceDto.getTagKeywordId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if(tagKeywordDeviceDto.getDeviceUniqueIds()==null&&!tagKeywordDeviceDto.getDeviceUniqueIds().isEmpty()){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        //查询关键词标签
        TaskTagKeyword taskTagKeyword= tagKeywordMapper.getById(tagKeywordDeviceDto.getTagKeywordId(),tagKeywordDeviceDto.getMerId());

        if(taskTagKeyword!=null){
            for (Long deviceUniqueId:tagKeywordDeviceDto.getDeviceUniqueIds()) {
                TaskTagKeywordDevice taskTagKeywordDevice = new TaskTagKeywordDevice();
                taskTagKeywordDevice.setMerId(taskTagKeyword.getMerId());
                taskTagKeywordDevice.setName(taskTagKeyword.getName());
                taskTagKeywordDevice.setTriggerType(taskTagKeyword.getTriggerType());
                taskTagKeywordDevice.setKeywordType(taskTagKeyword.getKeywordType());
                taskTagKeywordDevice.setKeywordModel(taskTagKeyword.getKeywordModel());
                taskTagKeywordDevice.setKeywords(taskTagKeyword.getKeywords());
                taskTagKeywordDevice.setEnterpriseTags(taskTagKeyword.getEnterpriseTags());
                taskTagKeywordDevice.setTaskId(taskTagKeyword.getId());
                taskTagKeywordDevice.setDeviceUniqueId(deviceUniqueId);
                taskTagKeywordDeviceMapper.addTaskTagKeywordDevice(taskTagKeywordDevice);
            }
        }

    }

    @Override
    public  MyPageInfo getTagKeywordList(TaskTagKeywordQuery taskTagKeywordQuery) {
        if(taskTagKeywordQuery.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }

        if(taskTagKeywordQuery.getParentTagId()!=null){
            CustomerTagQuery customerTagQuery=new CustomerTagQuery();
            customerTagQuery.setIfChild(1);
            customerTagQuery.setMerId(taskTagKeywordQuery.getMerId());
            customerTagQuery.setStatus(1);
            customerTagQuery.setType(1);
            customerTagQuery.setPid(taskTagKeywordQuery.getParentTagId());
            List<WwTags> wwTagsList = wwTagsMapper.getCustomerTag(customerTagQuery);
            if(wwTagsList==null||wwTagsList.isEmpty()){
                return new MyPageInfo(null);
            }
            List<Long> tagIds = wwTagsList.stream().map(WwTags::getId).distinct().collect(Collectors.toList());
            if(tagIds.isEmpty()){
                return new MyPageInfo(null);
            }
            taskTagKeywordQuery.setTagIds(tagIds);
        }



        String orderBy = OrderByUtil.getOrderBy(taskTagKeywordQuery.getOrderByField(), taskTagKeywordQuery.isAsc());
        PageHelper.startPage(taskTagKeywordQuery.getCurrent(),taskTagKeywordQuery.getSize(),orderBy);
        List<TaskTagKeywordVo> taskTagKeywordVoList = tagKeywordMapper.getTagKeywordList(taskTagKeywordQuery);
        if(taskTagKeywordVoList!=null&&!taskTagKeywordVoList.isEmpty()){
            for (TaskTagKeywordVo taskTagKeywordVo:taskTagKeywordVoList) {
                try {
                    if(taskTagKeywordVo.getEnterpriseTags()!=null){
                        ObjectMapper objectMapper1 = new ObjectMapper();
                        taskTagKeywordVo.setTriggerTypeList(objectMapper1.readValue(taskTagKeywordVo.getTriggerType(),List.class));
                    }

                    
                    //设置标签名
                    if(!StringUtils.isBlank(taskTagKeywordVo.getEnterpriseTags())){
                        ObjectMapper objectMapper=new ObjectMapper();
                        taskTagKeywordVo.setEnterpriseTagsList(objectMapper.readValue(taskTagKeywordVo.getEnterpriseTags(),List.class));
                        List<String> tagNames=new ArrayList<>();
                        for (Long tagId:taskTagKeywordVo.getEnterpriseTagsList()) {
                           try {
                               WwTags wwTags = wwTagsMapper.getById(tagId, taskTagKeywordVo.getMerId());
                               tagNames.add(wwTags.getTagName());
                           }catch (Exception e){
                               e.printStackTrace();
                           }
                        }
                        if(tagNames!=null&&!tagNames.isEmpty()){
                            taskTagKeywordVo.setEnterpriseTagNamesList(tagNames);
                        }
                    }
                    //设置关键词
                    if(!StringUtils.isBlank(taskTagKeywordVo.getKeywords())){
                        ObjectMapper objectMapper=new ObjectMapper();
                        taskTagKeywordVo.setKeywordsList(objectMapper.readValue(taskTagKeywordVo.getKeywords(), new TypeReference<List<String>>(){}));
                    }

                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }

        MyPageInfo myPageInfo = new MyPageInfo<>(taskTagKeywordVoList);
        return myPageInfo;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateTagKeyword(TaskTagKeywordDto taskTagKeywordDto) {
        if(taskTagKeywordDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(taskTagKeywordDto.getId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }

        TaskTagKeyword taskTagKeyword = tagKeywordMapper.getById(taskTagKeywordDto.getId(), taskTagKeywordDto.getMerId());
        if(taskTagKeyword==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION,"关键词规则不存在");
        }
        taskTagKeyword.setName(taskTagKeywordDto.getName());
        taskTagKeyword.setTriggerType(JSONObject.toJSONString(taskTagKeywordDto.getTriggerTypeList()));
        taskTagKeyword.setKeywordType(taskTagKeywordDto.getKeywordType());
        taskTagKeyword.setKeywordModel(taskTagKeywordDto.getKeywordModel());
        if(taskTagKeywordDto.getKeywordsList()!=null&&!taskTagKeywordDto.getKeywordsList().isEmpty()){
            taskTagKeyword.setKeywords(JSONObject.toJSONString(taskTagKeywordDto.getKeywordsList()));
        }
        if(taskTagKeywordDto.getEnterpriseTagsList()!=null&&!taskTagKeywordDto.getEnterpriseTagsList().isEmpty()){
            taskTagKeyword.setEnterpriseTags(taskTagKeywordDto.getEnterpriseTagsList().toString());
        }

        tagKeywordMapper.updateTagKeyword(taskTagKeyword);


        TaskTagKeywordDeviceQuery taskTagKeywordDeviceQuery=new TaskTagKeywordDeviceQuery();
        taskTagKeywordDeviceQuery.setTaskId(taskTagKeyword.getId());
        taskTagKeywordDeviceQuery.setMerId(taskTagKeyword.getMerId());
        List<TaskTagKeywordDeviceVo> taskTagKeywordDeviceList = taskTagKeywordDeviceMapper.getTaskTagKeywordDeviceList(taskTagKeywordDeviceQuery);
        if(taskTagKeywordDeviceList!=null&&!taskTagKeywordDeviceList.isEmpty()){
            for (TaskTagKeywordDeviceVo taskTagKeywordDeviceVo:taskTagKeywordDeviceList) {
                TaskTagKeywordDevice taskTagKeywordDevice = new TaskTagKeywordDevice();
                BeanUtil.copyProperties(taskTagKeywordDeviceVo,taskTagKeywordDevice);
                taskTagKeywordDevice.setName(taskTagKeyword.getName());
                taskTagKeywordDevice.setTriggerType(taskTagKeyword.getTriggerType());
                taskTagKeywordDevice.setKeywordType(taskTagKeyword.getKeywordType());
                taskTagKeywordDevice.setKeywordModel(taskTagKeyword.getKeywordModel());
                taskTagKeywordDevice.setKeywords(taskTagKeyword.getKeywords());
                taskTagKeywordDevice.setEnterpriseTags(taskTagKeyword.getEnterpriseTags());
                taskTagKeywordDeviceMapper.update(taskTagKeywordDevice);
            }
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleTagKeyword(DeleTagKeywordDto deleTagKeywordDto) {
        if(deleTagKeywordDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(deleTagKeywordDto.getId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        TaskTagKeyword taskTagKeyword = tagKeywordMapper.getById(deleTagKeywordDto.getId(), deleTagKeywordDto.getMerId());
        if(taskTagKeyword==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "关键词标签规则不存在");
        }
        //先删除关系
        TaskTagKeywordDeviceQuery taskTagKeywordDeviceQuery=new TaskTagKeywordDeviceQuery();
        taskTagKeywordDeviceQuery.setMerId(taskTagKeyword.getMerId());
        taskTagKeywordDeviceQuery.setTaskId(taskTagKeyword.getId());
        List<TaskTagKeywordDeviceVo> taskTagKeywordDeviceList= taskTagKeywordDeviceMapper.getTaskTagKeywordDeviceList(taskTagKeywordDeviceQuery);
        if(taskTagKeywordDeviceList!=null&&!taskTagKeywordDeviceList.isEmpty()){
            for (TaskTagKeywordDeviceVo  taskTagKeywordDevice:taskTagKeywordDeviceList) {
                taskTagKeywordDeviceMapper.deleById(taskTagKeywordDevice.getId(),taskTagKeywordDevice.getMerId());
            }
        }

        //再删除关键词标签规则
        tagKeywordMapper.deleById(taskTagKeyword.getId(),taskTagKeyword.getMerId());

    }


    @Override
    public Object getTagKeywordDevice(TaskTagKeywordDeviceQuery tagKeywordDeviceQuery) {
        if(tagKeywordDeviceQuery.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        //获取对应分组的机器人
        List<Long>deviceIds=new ArrayList<>();
        if(tagKeywordDeviceQuery.getGroupId()!=null){
            DeviceGroupRelationQuery deviceGroupRelationQuery = new DeviceGroupRelationQuery();
            deviceGroupRelationQuery.setGroupId(tagKeywordDeviceQuery.getGroupId());
            deviceGroupRelationQuery.setMerId(tagKeywordDeviceQuery.getMerId());
            List<DeviceGroupRelation> deviceGroupRelationList= deviceGroupRelationMapper.deviceGroupRelationList(deviceGroupRelationQuery);
            if(deviceGroupRelationList!=null&&!deviceGroupRelationList.isEmpty()){
                for (DeviceGroupRelation deviceGroupRelation:deviceGroupRelationList) {
                    try {
                        deviceIds.add(deviceGroupRelation.getDeviceUniqueId());
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
            if(deviceIds.isEmpty()){
                return new MyPageInfo<>(null);
            }
        }
        //通过关键词获取机器人ID
        List<Long> keywordDeviceIds=new ArrayList<>();
        if(!StringUtils.isBlank(tagKeywordDeviceQuery.getKeyword())) {
            WwDeviceQuery wwDeviceQuery = new WwDeviceQuery();
            wwDeviceQuery.setKeyword(tagKeywordDeviceQuery.getKeyword());
            wwDeviceQuery.setMerId(tagKeywordDeviceQuery.getMerId());
            List<WwDeviceVo> wwDeviceList = wwDeviceMapper.getWwDeviceList(wwDeviceQuery);
            if (wwDeviceList != null && !wwDeviceList.isEmpty()) {
                keywordDeviceIds = wwDeviceList.stream().map(WwDeviceVo::getId).distinct().collect(Collectors.toList());
            }
            if(keywordDeviceIds.isEmpty()){
                return new MyPageInfo<>(null);
            }
        }

        if(!deviceIds.isEmpty()&&keywordDeviceIds.isEmpty()){
            tagKeywordDeviceQuery.setDeviceIds(deviceIds);
        }
        if(deviceIds.isEmpty()&&!keywordDeviceIds.isEmpty()){
            tagKeywordDeviceQuery.setDeviceIds(keywordDeviceIds);
        }
        if(!deviceIds.isEmpty()&&!keywordDeviceIds.isEmpty()){
            List<Long> intersection = deviceIds.stream().filter(keywordDeviceIds::contains).collect(Collectors.toList());
            tagKeywordDeviceQuery.setDeviceIds(intersection);
        }

        String orderBy = OrderByUtil.getOrderBy(tagKeywordDeviceQuery.getOrderByField(), tagKeywordDeviceQuery.isAsc());
        PageHelper.startPage(tagKeywordDeviceQuery.getCurrent(),tagKeywordDeviceQuery.getSize(),orderBy);
        List<TaskTagKeywordDeviceVo> taskTagKeywordDeviceVoList=taskTagKeywordDeviceMapper.getTaskTagKeywordDeviceList(tagKeywordDeviceQuery);

        if(taskTagKeywordDeviceVoList!=null&&!taskTagKeywordDeviceVoList.isEmpty()){
            for (TaskTagKeywordDeviceVo taskTagKeywordDeviceVo:taskTagKeywordDeviceVoList) {
                WwDevice wwDevice = wwDeviceMapper.getById(taskTagKeywordDeviceVo.getDeviceUniqueId(), taskTagKeywordDeviceVo.getMerId());
                if(wwDevice!=null){
                    taskTagKeywordDeviceVo.setDeviceName(wwDevice.getDeviceName());
                    taskTagKeywordDeviceVo.setHeadImageUrl(wwDevice.getHeadImgUrl());
                }
            }
        }
        return new MyPageInfo<>(taskTagKeywordDeviceVoList);
    }

    @Override
    public void deleTagKeywordDevice(BatchDeleTagKeywordDeviceDto batchDeleTagKeywordDeviceDto) {
        if(batchDeleTagKeywordDeviceDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION,ResponseMsg.MERID_NULL);
        }
        if(batchDeleTagKeywordDeviceDto.getId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION,ResponseMsg.ID_NULL);
        }
        taskTagKeywordDeviceMapper.deleById(batchDeleTagKeywordDeviceDto.getId(),batchDeleTagKeywordDeviceDto.getMerId());
    }
}
